package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    /**
     * 获取用户名
     *
     * @return
     */
    @RequestMapping("/findUsername")
    @ResponseBody
    public Result findUsername(HttpServletRequest request) {
        try {
            //获取安全框架的上下文对象
            SecurityContext securityContext = SecurityContextHolder.getContext();
//        获取认证对象
            Authentication authentication = securityContext.getAuthentication();
            //获取User对象
            Object principal = authentication.getPrincipal();
            User user = (User) principal;
            //获取用户名
            String username = user.getUsername();
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }
    @RequestMapping("/findMenuByUsername")
    @ResponseBody  //返回json字符串啊
    public Result findMenuByUsername(String username){
        try {
            //根据用户名查询 角色 根据角色查菜单
            List<Map<String,Object>> mapList= userService.findMenuByUsername(username);
            return new Result(true, MessageConst.GET_MENU_SUCCESS,mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MENU_FAIL);
        }

    }
    @RequestMapping("/findByName")
    @ResponseBody  //返回json字符串啊
    public Result findByName(@RequestBody String username){
        String[] split = username.split("=");
        String s = split[0];
        System.out.println("s = " + s);
        try {
            System.out.println("username = " + username);
            long count=userService.findByname(s);
            if (count>0){
                return new Result(true,"正在修改请稍后",count);
            }else{
                return new Result(false,"没有该用户,请检查用户名");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改错误,请重试");
        }
    }
    @RequestMapping("/update")
    @ResponseBody  //返回json字符串啊
    public Result update(@RequestBody  Map<String,String> map){
        try {
            String username = map.get("name");
            System.out.println("username = " + username);
            String password = map.get("pass");
            long count=userService.findByname(username);
            if (count>0){
                userService.update(username,password);
                return new Result(true,"密码修改成功");
            }else{
                return new Result(false,"没有该用户,请检查用户名");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改错误,请重试");
        }
    }

    @RequestMapping("/doSuccess")
    public String doSuccess() {
        return "redirect:http://localhost:83/pages/main.html";
    }

    @RequestMapping("/doFail")
    public String doFail() {
        return "redirect:http://localhost:83/login.html?param=loginError";
    }
    //用户数据添加
    @ResponseBody
    @RequestMapping("/add")
    public Result add(@RequestBody SysUser user, Integer[] RoleIds) {
        try {
            //将前端穿过来的密码进行加密
            String password = user.getPassword();
            String encode = new BCryptPasswordEncoder().encode(password);
            user.setPassword(encode);

            userService.add(user,RoleIds);
            return new Result(true,MessageConst.ADD_USE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConst.ADD_USE_FAIL);

        }
    }
    //用户数据变更
    @ResponseBody
    @RequestMapping("/edit")
    public Result edit(@RequestBody SysUser user, Integer[] RolesIds ){
        try {
            userService.edit(user,RolesIds);
            return new Result(true,MessageConst.EDIT_USE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.EDIT_USE_FAIL);
        }
    }
    @ResponseBody
    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<SysUser>userList=userService.findAll();
            return new Result(true,MessageConst.QUERY_USER_SUCCESS,userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_USER_FAIL);
        }
    }
    @ResponseBody
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        PageResult pageResult = userService.findPage(queryPageBean);
        return pageResult;
    }
    @ResponseBody
    @RequestMapping("/delById")
    public Result delById(Integer id){
        try {
            userService.delById(id);
            return new Result(true,MessageConst.DELETE_USER_SUCCESS);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.DELETE_USER_FAIL);
        }
    }
    @ResponseBody
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            SysUser user=userService.findById(id);
            return new Result(true,MessageConst.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_USER_FAIL);

        }
    }

    @ResponseBody
    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer id){
        List<Integer> roleIdsList =userService.findRoleIdsByUserId(id);
        return new Result(true,"查询成功",roleIdsList);
    }

    @ResponseBody
    @RequestMapping("/findAllRoles")
    public Result findAllRoles(){
        List<Role> roleList =userService.findAllRoles();
        return new Result(true,"查询成功",roleList);
    }
}
